package com.liuzh.kaoyanspringboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liuzh.kaoyanspringboot.entity.Comment;
import com.liuzh.kaoyanspringboot.mapper.CommentMapper;
import com.liuzh.kaoyanspringboot.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 刘志鸿
 * @since 2023-03-11
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Resource
    private  CommentMapper commentMapper;
    @Override
    public List<Comment> findCommentDetail(Integer articleId) {
        // 查询所有的评论数据
        List<Comment> articleComments = commentMapper.findCommentDetail(articleId);
        // 查询一级评论
        List<Comment> orginComments = articleComments.stream().filter(comment -> comment.getOrginId() == null).collect(Collectors.toList());
        // 设置二级评论
        for (Comment orgin : orginComments) {
            List<Comment> children = articleComments.stream().filter(comment -> orgin.getId().equals(comment.getOrginId())).collect(Collectors.toList());  // 表示回复对象集合
            children.forEach(comment -> {
                articleComments.stream().filter(c1 -> c1.getId().equals(comment.getPid())).findFirst().ifPresent((v -> {     // 找到父级评论的用户id 和用户昵称并设置给当前的回复对象
                    comment.setPUserId(v.getUserId());
                    comment.setPNickname(v.getNickname());
                    comment.setPAvatarUrl(v.getAvatarUrl());
                }));
            });
            orgin.setChildren(children);
        }
        return orginComments;
    }


    @Override
    public boolean decrementLike(Integer id) {
        return commentMapper.decrementLike(id);
    }

    @Override
    public boolean increaseLike(Integer id) {
        return commentMapper.increaseLike(id);
    }

    @Override
    public Comment findById(Integer commentId) {
        return commentMapper.selectByCId(commentId);
    }

    /**
     * 根据被回复 ids 查询评论
     * @param replyCommentIds
     * @return
     */
    @Override
    public List<Comment> findReplyByIds(List<Integer> replyCommentIds) {
        return commentMapper.findReplyByIds(replyCommentIds);
    }

    @Override
    public List<Comment> findByPid(Integer pid) {
        return commentMapper.findByPid(pid);
    }

    /**
     * 根据 ids 批量查找
     * @param ids
     * @return
     */
    @Override
    public List<Comment> fListByIds(List<Integer> ids) {
        return commentMapper.fListByIds(ids);
    }

    @Override
    public Integer myCount() {
        return commentMapper.myCount();
    }


}
